package com.cskaoyan.utils;



import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * 创建日期: 2021/11/23 14:33
 *
 * @author ciggar
 */
public class JDBCUtils {

    static Connection connection;
    static String url;
    static String username;
    static String password;
    static String driverClassName;

    static {

        // 把用户名、密码、地址写到配置文件中
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("jdbc.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
        driverClassName = properties.getProperty("driverClassName");


        // 1. 注册驱动
//        try {
//            DriverManager.registerDriver(new Driver());
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }

//        new Driver();

        // 通过反射来创建对象
        try {
            Class.forName(driverClassName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


        // 2. 获取连接
        try {
            connection = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    // 获取连接
    public static Connection getConnection(){

        return connection;

    }

    // 关闭资源
    public static void closeReources(ResultSet resultSet, Statement statement,Connection connection){

        try {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }finally {
            try{
                if (statement != null) {
                    try {
                        statement.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }
}
